package com.chengfei.house.web.controller;

import com.chengfei.house.biz.service.UserService;
import com.chengfei.house.common.constants.CommonConstants;
import com.chengfei.house.common.model.User;
import com.chengfei.house.common.result.ResultMsg;
import com.chengfei.house.common.utils.HashUtils;
import com.chengfei.house.web.util.UserHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author chengfei cheng.fei@chinaott.onaliyun.com
 **/
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册提交：1：注册验证，2 发送邮件 3验证失败重定向到注册页面
     * 注册页提交：根据account对象为一句判断是否注册也获取请求
     * @param account
     * @param modelMap
     * @return
     */
    @RequestMapping("accounts/register")
    public String accountRegister(User account, ModelMap modelMap){
        if(account == null || account.getName() == null){
           return  "/user/accounts/register";
        }
        //用户验证
        ResultMsg resultMsg = UserHelper.valid(account);
        if(resultMsg.isSuccess() && userService.addAccount(account)){
            modelMap.put("email",account.getEmail());
            return "/user/accounts/registerSubmit";
        }else{
            return "redirect:/accounts/register?"+resultMsg.asUrlParams();
        }
    }

    @RequestMapping("accounts/verify")
    public String verify(String key){
        boolean result = userService.enable(key);
        if(result){
            return "redirect:/index?"+ResultMsg.successMsg("激活成功!").asUrlParams();
        }else{
            return "redirect:/accounts/register?"+ResultMsg.errorMsg("激活失败，请确认链接是否过期!");
        }
    }

    @RequestMapping("accounts/signin")
    public String signIn(HttpServletRequest request){
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String target = request.getParameter("target");
        if(userName == null || password == null){
            request.setAttribute("target",target);
            return "/user/accounts/signin";
        }
        User user = userService.auth(userName,password);
        if(user == null){
            return "redirect:/account/signin?"+"target"+target+"&username="+userName+"&"+ResultMsg
                    .errorMsg("用户名或者密码错误").asUrlParams();
        }else {
            HttpSession session = request.getSession(true);
            session.setAttribute(CommonConstants.USER_ATTRIBUTE,user);
//            session.setAttribute(CommonConstants.PLAIN_USER_ATTRIBUTE,user);
            return StringUtils.isNoneBlank(target)?"redirect:"+target:"redirect:/index";
        }
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @RequestMapping("accounts/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.invalidate();
        return "redirect:/index";
    }

    @RequestMapping("accounts/profile")
    public String profile(HttpServletRequest request,User updateUser,ModelMap modelMap){
        if(updateUser.getEmail() == null){
            return "/user/accounts/profile";
        }
        userService.updateUser(updateUser,updateUser.getEmail());
        User queryUser = new User();
        queryUser.setEmail(updateUser.getEmail());
        List<User> users =  userService.getUserByQuery(queryUser);
        request.getSession(true).setAttribute(CommonConstants.USER_ATTRIBUTE,users.get(0));
        return "redirect:/accounts/profile?"+
                ResultMsg.successMsg("更新成功")
                .asUrlParams();
    }

    @RequestMapping("accounts/changePassword")
    public String changePassword(String email,String password,String newPassword,String confirmPassword,ModelMap modelMap){
        User user = userService.auth(email,password);
        if(user == null || !confirmPassword.equals(newPassword)){
            return "redirect:/accounts/profile"+
                    ResultMsg.errorMsg("密码错误")
                    .asUrlParams();

        }
        User updateUser = new User();
        updateUser.setPasswd(HashUtils.encryPassword(newPassword));
        userService.updateUser(updateUser,email);
        return "redirect:/accounts/profile?"+ResultMsg.errorMsg("更新成功").asUrlParams();
    }

}
